package com.example.administrator.swredeem.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.swredeem.R;
import com.example.administrator.swredeem.appBase.Config;
import com.example.administrator.swredeem.beanClass.PayBean;
import com.example.administrator.swredeem.net.HttpXutils;
import com.example.administrator.swredeem.net.MyCallback;
import com.example.administrator.swredeem.utils.ZXingUtils;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

public class QRcodeActivity extends AppCompatActivity {

    @BindView(R.id.pay_ewm)
    ImageView payEwm;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.count_down)
    TextView countDown;
    private PayBean payBean;
    private Gson gson;
    private String title, userid, iccardno, gascount, gasfee, factory = "";
    private int duration = 2; //支付时长
    private CountDownTimer timer; //倒计时


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qrcode);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        userid = getIntent().getStringExtra("userid");
        iccardno = getIntent().getStringExtra("iccardno");
        gascount = getIntent().getStringExtra("gascount");
        gasfee = getIntent().getStringExtra("gasfee");
        title = getIntent().getStringExtra("title");
        factory = getIntent().getStringExtra("factory");
        payBean = new PayBean();
        gson = new Gson();
        money.setText("支付金额:" + gasfee + "元");
        net();

        timer = new CountDownTimer(duration * 60 * 1000, 100) {
            @Override
            public void onTick(long millisUntilFinished) {
                countDown.setText("倒计时:" + (millisUntilFinished / 1000) + "s");
//                Log.d("TAG", "onTick: "+millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                Log.d("TAG", "onFinish:倒计时结束！！！ ");
                countDown.setText("倒计时:0s");
                Toast.makeText(QRcodeActivity.this, "支付超时", Toast.LENGTH_SHORT).show();
                finish();

            }
        };
    }

    public void goRechargeSucceed(View v) {
        if (TextUtils.isEmpty(title)) {
            startActivity(new Intent(QRcodeActivity.this, RechargeSucceedActivity.class));
        } else {
            if (title.equals("开卡")) {
                startActivity(new Intent(QRcodeActivity.this, QCsucceedActivity.class));
            } else if (title.equals("补卡")) {
                startActivity(new Intent(QRcodeActivity.this, QCsucceedActivity.class));
            }

        }
    }

    public void net() {
        Map<String, String> map = new HashMap<>();
        map.put("spotno", "1");
        map.put("operno", "1");
        map.put("orgcode", "1");
        map.put("dataorgid", "1");
        map.put("userid", userid);
        map.put("iccardno", iccardno);
        map.put("gascount", gascount);
        map.put("gasfee", gasfee);
        map.put("duration", duration + "");

//        Log.d("TAG", "init: =" + TextUtils.isEmpty(huhao) + TextUtils.isEmpty(idCrad));
        HttpXutils.getData(Config.Pay, map, new MyCallback() {
            @Override
            public void onSuccess(String result) {
                Log.d("TAG", "onSuccess: " + result);
                payBean = gson.fromJson(result, PayBean.class);
                generatetheqrcode(payBean.getPayqrcode());
                timer.start();
                result(payBean.getFlowno());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }
        });
    }

    public void result(final String flowno) {
        RequestParams params = new RequestParams(Config.PayResult);
        params.addQueryStringParameter("spotno", "1");
        params.addQueryStringParameter("operno", "1");
        params.addQueryStringParameter("orgcode", "1");
        params.addQueryStringParameter("dataorgid", "1");
        params.addQueryStringParameter("userid", userid);
        params.addQueryStringParameter("iccardno", "1");
        params.addQueryStringParameter("flowno", flowno);
        params.addQueryStringParameter("duration", duration + "");

        params.setConnectTimeout(duration * 60 * 1000);
        // 获取所有键值对对象的集合
        Log.i("dylan", "请求链接：" + params.toString());

        x.http().get(params, new MyCallback() {
            @Override
            public void onSuccess(String result) {
                Log.d("TAG", "onSuccess: " + result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String code = jsonObject.getString("recode");
                    if (code.equals("0000")) {
                        ICpay(flowno);
                    } else {
                        Toast.makeText(QRcodeActivity.this, jsonObject.getString("remsg"), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("TAG", "onSuccess: " + ex.getMessage());
            }
        });
    }

    //IC卡充值
    public void ICpay(String flowno) {
        Map<String, String> map = new HashMap<>();
        map.put("spotno", "1");
        map.put("operno", "1");
        map.put("orgcode", "1");
        map.put("dataorgid", "1");
        map.put("userid", userid);
        map.put("outbusisn", flowno);
        map.put("cardid", "");
        map.put("amount", gascount);
        map.put("busitype", 1 + "");
        if(factory.equals("先锋")){//cardtype 是 IC卡类型1先锋2威星(暂定)
            map.put("cardtype", 1 + "");
        }else if(factory.equals("威星")){
            map.put("cardtype", 2 + "");
        }


//        Log.d("TAG", "init: =" + TextUtils.isEmpty(huhao) + TextUtils.isEmpty(idCrad));
        HttpXutils.getData(Config.ICPay, map, new MyCallback() {
            @Override
            public void onSuccess(String result) {
                Log.d("TAG", "onSuccess: " + result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String code = jsonObject.getString("recode");

                    if (code.equals("0000")) {
                        String busisn = jsonObject.getString("busisn");
                        Log.d("TAG", "onSuccess:IC卡充值成功——圈存流水号" + busisn);
                        finish();
                        startActivity(new Intent(QRcodeActivity.this, RechargeSucceedActivity.class));
                    } else {
                        Toast.makeText(QRcodeActivity.this, jsonObject.getString("remsg"), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }
        });
    }


    /**
     * 生成支付二维码
     *
     * @param url
     */
    public void generatetheqrcode(String url) {
        Bitmap bm = ZXingUtils.createQRImage(url, 500, 500);
        payEwm.setImageBitmap(bm);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}
